package com.atguigu.lease.web.app.custom.interceptor;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.web.app.context.LoginUserContext;
import com.atguigu.lease.web.app.service.UserInfoService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * ClassName:AuthenticationInterceptor
 * Package: com.atguigu.lease.web.app.custom.interceptor
 * Description:
 *
 * @Author Makabaka
 * @Create 2024/9/27 18:41
 * @Version 1.0
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private UserInfoService userInfoService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        检查是否有token  有对token进行解析  获取到包含的用户id  获取用户 添加到ThreadLocal中 用于共享数据
        String getToken = request.getHeader("access_token");
        if (getToken == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }
        Long userId = JwtUtil.parseToken(getToken);
        LoginUserContext.setLoginUser(userInfoService.getById(userId));
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();
    }
}
